package com.vf.admin.client.controller;

import com.alibaba.fastjson.JSONObject;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppAuthDao;
import com.vf.admin.client.param.UpdateDongTaiWebParam;
import com.vf.admin.client.service.*;
import com.vf.admin.common.BaiDuAuthUtil;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.vf.admin.common.Constants.dongtai_length;
import static com.vf.admin.common.Constants.shengfengzheng;

@RestController
@RequestMapping("/app/auth")
public class ApiAuthController extends ClientBaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppAuthService authService;
    @Autowired
    AppAuthUserService appAuthUserService;
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppVoiceSignatureService appVoiceSignatureService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    AppAuthDao appAuthDao;
    @Autowired
    AppInvitationRecordService appInvitationRecordService;


    /**
     * 手动认证 实名加真人
     */
    @PostMapping(value = "/updateRealNameWeb")
    @ResponseBody
    public Result updateRealNameWeb(@RequestBody UpdateDongTaiWebParam param) {
        String[] split = param.getUserIds().split(",");
        List<String> userIdList = Arrays.asList(split);
        userIdList.forEach(e -> {
            appAuthUserService.addUserAuth(Integer.valueOf(e), ClientConstants.UserAuth.REAL_NAME_AUTH, null, null, null, null);
            appAuthUserService.addUserAuthAuditNot(Integer.valueOf(e), ClientConstants.UserAuth.REAL_AUTH, null, null, null, null);
            appUserService.updateRealName(Integer.valueOf(e), null, null);
        });
        return this.sucessJSON("成功");
    }


    /**
     * 手动认证 实名加真人
     */
    @RequestMapping(value = "/updateRealName")
    public Result updateRealName(String userIds) {
        String[] split = userIds.split(",");
        List<String> userIdList = Arrays.asList(split);
        userIdList.forEach(e -> {
            appAuthUserService.addUserAuth(Integer.valueOf(e), ClientConstants.UserAuth.REAL_NAME_AUTH, null, null, null, null);
            appAuthUserService.addUserAuthAudit(Integer.valueOf(e), ClientConstants.UserAuth.REAL_AUTH, null, null, null, null);

            appUserService.updateRealName(Integer.valueOf(e), null, null);
        });
        return this.sucessJSON("成功");
    }

    /**
     * 认证列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/authItemList")
    public Result authItemList(HttpServletRequest request) {
        Map<String, Object> data = new HashMap<>();
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));

        List<AppAuth> list = new ArrayList<>();
        Map<String, Integer> userAuthStatusMap = appAuthUserService.infoMapByUser(userId);
        List<AppAuth> itemList = authService.list();
        for (AppAuth appAuth : itemList) {
            Integer status = userAuthStatusMap.get(appAuth.getAuthNameEn());
            if (status == 2) {
                list.add(appAuth);
            }

            appAuth.setStatus(status);
        }
        itemList.removeAll(list);
        itemList.addAll(list);

        data.put("list", itemList);
        return this.sucessJSON(data);
    }

    /**
     * 真人认证
     *
     * @param request
     * @param realPic
     * @return
     */
    @RequestMapping(value = "/realAuth")
    public Result authItemList(HttpServletRequest request, String realPic) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser appUser = appUserService.get(userId);
        AppSetup appSetup = appSetupService.get();

        AppAuthUser appAuthUser = appAuthUserService.infoByUserAndNameB(userId, ClientConstants.UserAuth.REAL_AUTH);
        if (appAuthUser != null) {
            if (appAuthUser.getStatus() == 1) {
                return this.errorJSON("认证信息审核中，请稍后！");
            } else if (appAuthUser.getStatus() == 2) {
                return this.errorJSON("认证信息已通过，请勿重复提交！");
            }
        }

        JSONObject jsonObject = BaiDuAuthUtil.match(redisUtil, appUser.getPic(), realPic);
        logger.info("人脸比对结果：{}", jsonObject);
        if (StringUtils.equals("SUCCESS", jsonObject.getString("error_msg"))) {
            JSONObject resultJson = jsonObject.getJSONObject("result");
            Double matchScore = resultJson.getDouble("score");
            if (matchScore > appSetup.getFaceCompScore()) {
                appAuthUserService.addUserAuthAudit(userId, ClientConstants.UserAuth.REAL_AUTH, appUser.getPic(), realPic, null, null);
                return this.sucessJSON("成功");
            } else {
                return this.errorJSON("认证失败");
            }
        } else {
            return this.errorJSON("认证失败");
        }
    }

    /**
     * 实名认证
     *
     * @param request
     * @param realName
     * @param idNum
     * @return
     */
    @RequestMapping(value = "/realNameAuth")
    public Result realNameAuth(HttpServletRequest request, String realName, String idNum, String image) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppSetup appSetup = appSetupService.get();

        AppAuthUser appAuthUser = appAuthUserService.infoByUserAndNameB(userId, ClientConstants.UserAuth.REAL_NAME_AUTH);
        if (appAuthUser != null) {
            if (appAuthUser.getStatus() == 1) {
                return this.errorJSON("认证信息审核中，请稍后！");
            } else if (appAuthUser.getStatus() == 2) {
                return this.errorJSON("认证信息已通过，请勿重复提交！");
            }
        }

        JSONObject jsonObject = BaiDuAuthUtil.verify(redisUtil, realName, idNum, image);
        logger.info("实名认证结果：{}", jsonObject);
        JSONObject result = jsonObject.getJSONObject("result");
        if (result == null || result.getIntValue("verify_status") != BaiDuAuthUtil.VERIFY_STATUS) {
            return this.errorJSON("身份信息有误");
        }
        JSONObject resultJson = jsonObject.getJSONObject("result");
        Double matchScore = resultJson.getDouble("score");
        if (matchScore > appSetup.getFaceCompScore()) {
            AppUser user = appUserService.get(userId);
            int s = Integer.valueOf(idNum.substring(16, 17));
            if (user.getSex() == 1) {
                if (s % 2 != 0) {
                    //奇数男
                } else {
                    //偶数女
//                    return this.errorJSON("性别不匹配！");
                }
            } else if (user.getSex() == 2) {
                if (s % 2 != 0) {
                    //奇数男
//                    return this.errorJSON("性别不匹配！");
                } else {
                    //偶数女
                }
            }
            //查询名字和身份证号是否已使用
            boolean exists = appUserService.existsNameAndIdNum(realName, idNum);
            if (exists) {
//                return this.errorJSON("此认证信息已存在！");
            }

            appAuthUserService.addUserAuth(userId, ClientConstants.UserAuth.REAL_NAME_AUTH, image, null, realName, idNum);
            appUserService.updateRealName(userId, realName, idNum);
            appDailyTasController.getAwardOnce(userId, ClientConstants.TaskOnce.REAL_NAME);

            //给上级奖励
            AppInvitationRecord invitationRecord = appInvitationRecordService.getShangji(userId);
            if (invitationRecord != null) {
                AppSetup setup = appSetupService.get();
                //增加上级邀请人金币
                appUserService.addDiamonds(invitationRecord.getPuserid(), new BigDecimal(setup.getRenzhengfanli()), "下级认证奖励");
            }
            return this.sucessJSON("成功");
        }
        return this.errorJSON("身份信息有误");
    }


    /**
     * 实名认证
     *
     * @param request
     * @param realName
     * @param idNum
     * @return
     */
    @RequestMapping(value = "/realNameAuthIos")
    public Result realNameAuthIos(HttpServletRequest request, String realName, String idNum, String image) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppSetup appSetup = appSetupService.get();

        if (idNum.trim().length() > shengfengzheng) {
            return this.errorJSON("身份证长度最多" + shengfengzheng + "位数");
        }

        AppAuthUser appAuthUser = appAuthUserService.infoByUserAndNameB(userId, ClientConstants.UserAuth.REAL_NAME_AUTH);
        if (appAuthUser != null) {
            if (appAuthUser.getStatus() == 1) {
                return this.errorJSON("认证信息审核中，请稍后！");
            } else if (appAuthUser.getStatus() == 2) {
                return this.errorJSON("认证信息已通过，请勿重复提交！");
            }
        }

        appAuthUserService.addUserAuth(userId, ClientConstants.UserAuth.REAL_NAME_AUTH, image, null, realName, idNum);
        appUserService.updateRealName(userId, realName, idNum);
        appDailyTasController.getAwardOnce(userId, ClientConstants.TaskOnce.REAL_NAME);

        //给上级奖励
        AppInvitationRecord invitationRecord = appInvitationRecordService.getShangji(userId);
        if (invitationRecord != null) {
            AppSetup setup = appSetupService.get();
            //增加上级邀请人金币
            appUserService.addDiamonds(invitationRecord.getPuserid(), new BigDecimal(setup.getRenzhengfanli()), "下级认证奖励");
        }
        return this.sucessJSON("成功");

    }

    /**
     * 随机一个语音签名文案
     *
     * @return
     */
    @RequestMapping(value = "/randomSignatureOne")
    public Result randomOne() {
        AppVoiceSignature appVoiceSignature = appVoiceSignatureService.randomOne();
        return this.sucessJSON(appVoiceSignature);
    }

    /**
     * 设置我的语音签名
     *
     * @return
     */
    @RequestMapping(value = "/voiceSignature")
    public Result voiceSignature(String voiceUrl, @RequestParam(value = "seconds", defaultValue = "0") Integer seconds) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));

        AppAuthUser appAuthUser = appAuthUserService.infoByUserAndNameB(userId, ClientConstants.UserAuth.VOICE);
        if (appAuthUser != null) {
            if (appAuthUser.getStatus() == 1) {
                return this.errorJSON("认证信息审核中，请稍后！");
            } else if (appAuthUser.getStatus() == 2) {
                //return this.errorJSON("认证信息已通过，请勿重复提交！");
            }
        }

        appAuthUserService.addUserAuthAudit(userId, ClientConstants.UserAuth.VOICE, voiceUrl, null, String.valueOf(seconds), null);

        AppUser appUser = appUserService.get(userId);
        appUser.setVoiceSignature(null);
        appUser.setVoiceSignatureSeconds(null);
        appUser.setVoiceSignatureParse(0);
        appUserService.update(appUser);
        return this.sucessJSON("成功");
    }

    /**
     * 学历认证
     *
     * @return
     */
    @RequestMapping(value = "/eduAuth")
    public Result eduAuth(String image, String image2, String school, String education) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));

        AppAuthUser appAuthUser = appAuthUserService.infoByUserAndNameB(userId, ClientConstants.UserAuth.EDU_AUTH);
        if (appAuthUser != null) {
            if (appAuthUser.getStatus() == 1) {
                return this.errorJSON("认证信息审核中，请稍后！");
            } else if (appAuthUser.getStatus() == 2) {
                return this.errorJSON("认证信息已通过，请勿重复提交！");
            }
        }

        appAuthUserService.addUserAuthAudit(userId, ClientConstants.UserAuth.EDU_AUTH, image, image2, school, education);

        return this.sucessJSON("成功");
    }

    /**
     * 车辆认证
     *
     * @param image
     * @param image2
     * @param carBrand
     * @return
     */
    @RequestMapping(value = "/carAuth")
    public Result carAuth(String image, String image2, String carBrand) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));

        AppAuthUser appAuthUser = appAuthUserService.infoByUserAndNameB(userId, ClientConstants.UserAuth.CAR_AUTH);
        if (appAuthUser != null) {
            if (appAuthUser.getStatus() == 1) {
                return this.errorJSON("认证信息审核中，请稍后！");
            } else if (appAuthUser.getStatus() == 2) {
                return this.errorJSON("认证信息已通过，请勿重复提交！");
            }
        }

        appAuthUserService.addUserAuthAudit(userId, ClientConstants.UserAuth.CAR_AUTH, image, image2, carBrand, null);

        return this.sucessJSON("成功");
    }

    /**
     * 房产认证
     *
     * @param image
     * @param image2
     * @return
     */
    @RequestMapping(value = "/houseAuth")
    public Result houseAuth(String image, String image2) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));

        AppAuthUser appAuthUser = appAuthUserService.infoByUserAndNameB(userId, ClientConstants.UserAuth.HOUSE_AUTH);
        if (appAuthUser != null) {
            if (appAuthUser.getStatus() == 1) {
                return this.errorJSON("认证信息审核中，请稍后！");
            } else if (appAuthUser.getStatus() == 2) {
                return this.errorJSON("认证信息已通过，请勿重复提交！");
            }
        }

        appAuthUserService.addUserAuthAudit(userId, ClientConstants.UserAuth.HOUSE_AUTH, image, image2, null, null);

        return this.sucessJSON("成功");
    }

    /**
     * 获取百度人脸识别德token
     */
    @GetMapping(value = "/getAccessToken")
    public Result getAccessToken() {
        String accessToken = BaiDuAuthUtil.getAccessToken(redisUtil);
        System.out.println(accessToken);
        return this.sucessJSON(accessToken, "成功");
    }

}
